package com.example.demo.controller;

import com.example.demo.domain.dto.ResultDTO;

import com.example.demo.domain.po.Role;
import com.example.demo.domain.po.UserStatus;
import com.example.demo.services.UserServices;
import com.example.demo.services.impl.UserServicesImpl;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")

public class UserController {
    public static String user;
    @Autowired
    UserServices userServices;

    ResultDTO resultDTO = new ResultDTO();

    public boolean isAdmin(){
        return UserServicesImpl.role == Role.admin;
    }

    public boolean isActivated(){
        return UserServicesImpl.userStatus == UserStatus.active;
    }

    @PostMapping("/login")
    public ResultDTO login(@Param("username") String username,@Param("password") String password) {

        //获取全局用户账号以获取用户token -> MyInterceptor
        user = username;
        String token = userServices.login(username, password);
        //发向前端的基础信息设置
        resultDTO.setMessage(UserServicesImpl.nickname);
        resultDTO.setData(token);
        resultDTO.setAdmin(isAdmin());
        resultDTO.setActivated(isActivated());
        resultDTO.setBorrow_limit(UserServicesImpl.borrow_limit);
        resultDTO.setBorrow_duration(UserServicesImpl.borrow_duration);
        resultDTO.setExtend_limit(UserServicesImpl.extend_limit);
        resultDTO.setExtend_duration(UserServicesImpl.extend_duration);

        return resultDTO;
    }
    @GetMapping("logout")
    public ResultDTO logout(){
        userServices.logout();
        resultDTO.setMessage("您已成功注销！");
        return resultDTO;
    }
    //TODO 注册待修改
    @PostMapping("register")
    public ResultDTO register(@Param("nickname")String nickname,@Param("username") String username,@Param("password") String password ,@Param("state")String state) {
        System.out.println("前端的选择是 "+state);
        userServices.register(nickname,username,password);
        resultDTO.setMessage("恭喜您注册成功！");
        return resultDTO;
    }
    @PostMapping("update")
    public ResultDTO update(@Param("username") String username,@Param("password") String password) {
        userServices.changePassword(username,password);
        resultDTO.setMessage("您的密码已更新！请重新登录！");
        return resultDTO;
    }
}
